package com.hilon.segment.mybatis.service.impl;

import com.hilon.segment.mybatis.pojo.dto.MyGrantedAuthorityDTO;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

@Service
public class AccessDecisionManagerImpl implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();

        AntPathRequestMatcher matcher;
        String method, url;

        for (GrantedAuthority grantedAuthority :
                authentication.getAuthorities()) {
            if (grantedAuthority instanceof MyGrantedAuthorityDTO myGrantedAuthorityDTO) {
                method = myGrantedAuthorityDTO.getMethod();
                url = myGrantedAuthorityDTO.getUrl();
                matcher = new AntPathRequestMatcher(url);
                if (matcher.matches(request)) {
                    if (method.equals(request.getMethod()) || "ALL".equals(method)) {
                        return;
                    }
                }
            } else if (grantedAuthority.getAuthority().equals("ROLE_ANONYMOUS")) {
                // ROLE_ANONYMOUS 为匿名角色, 可以理解成未登录状态.
                // 此处, 未登录仅允许访问 login 接口
                matcher = new AntPathRequestMatcher("/login");
                if (matcher.matches(request)) {
                    return;
                }

            }
        }

        throw new AccessDeniedException("no right");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
